package com.guazi.trackingtest;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.guazi.trackingtest.Utils.TYPE_ACC;
import static com.guazi.trackingtest.Utils.TYPE_GYR;
import static com.guazi.trackingtest.Utils.TYPE_LINEAR_ACC;
import static com.guazi.trackingtest.Utils.TYPE_MAG;
import static com.guazi.trackingtest.Utils.sensorEvent2PackData;

public class MainActivity extends AppCompatActivity {

    private SensorManager mSensorManager;
    private Sensor mGyr;//陀螺仪
    private Sensor mAcc;//加速计
    private Sensor mLAcc;//线性加速计
    private Sensor mMag;//磁力计

    private static final double N2S = 1000000000D;

    @BindView(R.id.main_ac_error_detect_tv)
    TextView mErrorDetectTv;
    @BindView(R.id.main_ac_reset_btn)
    Button mRestBtn;

    private Sender mSender;
    private Filter mFilter;

    private volatile boolean log = false;

    private long time = 0L;
    private double distance = 0L;

    private SensorEventListener mGyrSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            Message message = Message.obtain();
            message.what = TYPE_GYR;
            message.obj = event;
            mHandler.sendMessage(message);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    private SensorEventListener mAccSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            Message message = Message.obtain();
            message.what = TYPE_ACC;
            message.obj = event;
            mHandler.sendMessage(message);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    private SensorEventListener mLAccSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            Message message = Message.obtain();
            message.what = TYPE_LINEAR_ACC;
            message.obj = event;
            mHandler.sendMessage(message);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    private SensorEventListener mMagSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            Message message = Message.obtain();
            message.what = TYPE_MAG;
            message.obj = event;
            mHandler.sendMessage(message);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case TYPE_GYR:
                    sendGyrEvent((SensorEvent) msg.obj);
                    break;
                case TYPE_ACC:
                    break;
                case TYPE_MAG:
                    break;
                case TYPE_LINEAR_ACC:
                    sendLaccEvent((SensorEvent) msg.obj);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        assert mSensorManager != null;

        mGyr = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        mAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mLAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        mMag = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        if (null != mGyr)
            mSensorManager.registerListener(mGyrSensorEventListener, mGyr, SensorManager.SENSOR_DELAY_FASTEST);
//            if (null != mAcc)
//            mSensorManager.registerListener(mAccSensorEventListener, mAcc, SensorManager.SENSOR_DELAY_UI);
//                if (null != mMag)
//            mSensorManager.registerListener(mMagSensorEventListener, mMag, SensorManager.SENSOR_DELAY_NORMAL);
        if (null != mLAcc)
            mSensorManager.registerListener(mLAccSensorEventListener, mLAcc, SensorManager.SENSOR_DELAY_FASTEST);

        initJsSender();

//        Fragment fragment = Fragment.instantiate(this, "dsaf");
//        FragmentManager manager = getFragmentManager();
//        FragmentTransaction transaction = manager.beginTransaction();
//        transaction.add(R.id.sada, fragment);
//        transaction.commit();
//
//        Picasso.Builder

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(mLAccSensorEventListener);
        mHandler.removeCallbacksAndMessages(null);
        if (mSender != null) {
            mSender.stop();
        }
    }

    public void reset(View view) {
        if (mFilter != null) {
            mFilter.reQuiet();
        }
    }

    private void initJsSender() {

        if (mSender == null) {
            mSender = new Sender();
            mSender.start();
            mFilter = new Filter(10, mSender);
            mFilter.setQuietListener(new Filter.QuietListener() {
                @Override
                public void beingQuiet() {
                    mErrorDetectTv.setText("传感器误差检测中");
                }

                @Override
                public void finishQuiet(float defaultQuiet) {
                    mErrorDetectTv.setText("误差检测完毕 误差->" + defaultQuiet + "（m/s2）");
                }
            });
            Toast.makeText(this, "sender初始化成功", Toast.LENGTH_SHORT).show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            mSender.sendDataToJs();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    private void sendGyrEvent(SensorEvent event) {
//        if (mSender != null) {
//            mSender.addPackData(sensorEvent2PackData(event, TYPE_GYR));
//        }
    }

    private void sendLaccEvent(SensorEvent event) {
        if (mSender != null) {
            mSender.addPackData(sensorEvent2PackData(event, TYPE_LINEAR_ACC));
        }
//        if (mFilter != null) {
//            mFilter.addSensorEvent(event);
//        }
    }
}
